package com.electric.qrapp.utils.function

import com.google.gson.Gson
import com.google.gson.reflect.TypeToken

/**
 * @author created by WA03675
 * @date 2021-09-26 15:05
 * @des  GsonUtils
 */
object GsonUtils {
    private val gson: Gson by lazy {
        Gson()
    }

    /**
     * 转成json
     *

     */
    fun gsonString(obj: Any?): String? {
        var gsonString: String? = null
        if (gson != null) {
            gsonString = gson!!.toJson(obj)
        }
        return gsonString
    }

    /**
     * 转成bean
     *
     * @param gsonString
     * @param cls
     * @return
     */
    fun <T> gsonToBean(gsonString: String?, cls: Class<T>?): T? {

           return  gson.fromJson(gsonString, cls)

    }



    /**
     * 转成list中有map的
     *
     * @param gsonString
     * @return
     */
    fun <T> gsonToListMaps(gsonString: String?): List<Map<String, T>>? {
        var list: List<Map<String, T>>? = null
        if (gson != null) {
            list = gson!!.fromJson(
                gsonString,
                object : TypeToken<List<Map<String?, T>?>?>() {}.type
            )
        }
        return list
    }

    /**
     * 转成map的
     *
     * @param gsonString
     * @return
     */
    fun <T> gsonToStringMaps(gsonString: String?): Map<String, T>? {
        var map: Map<String, T>? = null
        if (gson != null) {
            map = gson!!.fromJson(gsonString, object : TypeToken<Map<String?, T>?>() {}.type)
        }
        return map
    }

    /**
     * 转成List的
     *
     * @param gsonString
     * @return
     */
    fun <T> gsonToList(gsonString: String?):List<T>? {
        var list = emptyList<T>()
         list = gson.fromJson(gsonString, object : TypeToken<List<T>>() {}.type)

        return list
    }

    /**
     * 转成map的
     *
     * @param gsonString
     * @return
     */

    fun <T, E> gsonToTMap(gsonString: String?): HashMap<T, E>? {
        var map: HashMap<T, E>? = null
        if (gson != null) {
            map = gson!!.fromJson(gsonString, object : TypeToken<Map<T, E>?>() {}.type)
        }
        return map
    }
}

